﻿using Common.Msg;
using DB;
using System;
using System.Diagnostics;
using System.Text;

namespace CToolsWin.DAL
{
    public class DBInit
    {
        private static DBHelpers db = DBFactorys.GetDBHelper();
        /// <summary>
        /// 删除指定表
        /// 谨慎使用！
        /// </summary>
        public static bool DeleteTable(string tableName)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("DROP TABLE [dbo].[{0}];", tableName);
                return db.ExecteNonQueryText(sb.ToString()) > 0;
            }
            catch (Exception ex)
            {
                if (ex.Message.Equals(string.Format("无法对 表 'dbo.{0}' 执行 删除，因为它不存在，或者您没有所需的权限。", tableName)))
                {
                    Log.GetLog.Warn(string.Format("初始化数据库时删除表'dbo.{0}'失败，原表不存在", tableName), typeof(DBInit));
                }
                else
                {
                    Log.GetLog.Error(string.Format("初始化数据库时删除表'dbo.{0}'错误", tableName), typeof(DBInit), ex);
                    throw ex;
                }
                return false;
            }
        }
        /// <summary>
        /// 删除指定表
        /// 谨慎使用！
        /// </summary>
        public static bool TruncateTable(string tableName)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("TRUNCATE TABLE [dbo].[{0}];", tableName);
                db.ExecteNonQueryText(sb.ToString());
                return true;
            }
            catch (Exception ex)
            {
                Log.GetLog.Error(string.Format("初始化数据库时删除表'dbo.{0}'错误", tableName), typeof(DBInit), ex);
                return false;
            }
        }
    }
}
